#!/usr/bin/env python3.11
# -*- encoding: utf-8 -*-
'''
@File    :   schemas.py
@Time    :   2024/02/20 16:55:31
@Author  :   windstarry 
@Version :   1.0
'''
# here put the import lib
from ninja_schema import model_validator

from typing import Any, Optional
from django.db import transaction
from ninja_extra import service_resolver
from ninja_extra.controllers import RouteContext
from ninja_extra.exceptions import APIException
from .models import Question,QuestionLevel,QuestionType,QuestionOption,QuestionCategory
from core.schemas import CoreModelSchema

class QuestionCategorySchema(CoreModelSchema):
    class Config:
        model = QuestionCategory
        include = ("id", "name", "tag", "description")


class CreateQuestionCategorySchema(CoreModelSchema):
    class Config:
        model = QuestionCategory
        optional = ["creator",]
        include = ("name", "tag", "description")
        
    @model_validator("tag")
    def unique_tag(cls, value_data):
        context: RouteContext = service_resolver(RouteContext)
        if not QuestionCategory.objects.filter(tag=value_data).exists():
            return value_data
        elif context.kwargs.get("c_id"):
            if QuestionCategory.objects.filter(
                tag=value_data, id=context.kwargs.get("c_id")
            ).exists():
                return value_data
        raise APIException("题目分类tag已存在")
    
    @transaction.atomic
    def create_obj(self, **kwargs: Any):
        _data = self.dict(exclude_none=True)
        _data.update(kwargs)
        return QuestionCategory.objects.create(**_data)
